package org.grow.jssp.controller;

import org.grow.jssp.dao.DownloadlogMapper;
import org.grow.jssp.entity.Downloadlog;
import org.grow.jssp.service.FileLambdaOps;
import org.grow.jssp.service.FileOps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author:宿世新
 * @Dte:2022/3/11
 */
@Controller
public class DownLoadController {
    @Value("${target}")
    private String target;

    /**
     * 访问待下载文件
     */
    @Autowired
    private FileOps fileOps;
    @Autowired
    private FileLambdaOps fileLambdaOps;
    @Autowired
    private DownloadlogMapper downloadlogMapper;

    @GetMapping("/repository")
    public ModelAndView repository(HttpServletRequest request) {

        //将target的值通过注解的方式来完成 注解在application.properties
//        String target = System.getProperty("user.home");
//        target = "D:\\modian";
        System.out.println(target);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("repo");
        modelAndView.addObject("list", fileLambdaOps.ops(target));
        return modelAndView;
    }

    @GetMapping("/repo.jsp/{fileName}")
    public void downLoad(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException {
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        System.out.println(fileName);
        System.out.println("将要下载:" + fileName);
        //将target的值通过注解的方式来完成
//        String target = System.getProperty("user.home");
//        target = "D:\\modian";
        //打印文件前缀名
        System.out.println(target);
        String t = target + File.separator + fileName;
        System.out.println("将要下载的文件全名" + t);
        //length为多大
        long length = new File(t).length();
//        response.addHeader("Content-Disposition", "attachment;filename" + t);
        ContentDisposition build = ContentDisposition.attachment().filename(fileName, StandardCharsets.UTF_8).build();
        response.addHeader(HttpHeaders.CONTENT_DISPOSITION, build.toString());
        System.out.println("将要下载的文件大小" + length);

        Downloadlog downloadlog = new Downloadlog();
        downloadlog.setDownloadTime(LocalDateTime.now());
        downloadlog.setFileName(fileName);
        downloadlog.setTargetFile(t);
        downloadlog.setState("processing");
        String principle = (String) request.getSession().getAttribute("principle");
        downloadlog.setUserName(principle);
        try {
            byte[] buffer = new byte[1];
            BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(t));
            BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            //一次读写
//        int r = inputStream.read(buffer);
//        outputStream.write(buffer, 0, r);
            int r;
            while ((r = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, r);
                System.out.println(r);
            }
            outputStream.flush();
            downloadlog.setState("success");
        } catch (Exception e) {
            System.out.println("failure");
            e.printStackTrace();
        } finally {
            downloadlogMapper.insert(downloadlog);
        }
        //测试mybaits
        List<Downloadlog> downloadlogs = downloadlogMapper.findList();
        System.out.println(downloadlogs);
        response.flushBuffer();
    }


}
